from app.models.user import UserCreate, UserInDB, User
from app.database.connection import get_database
from app.core.security import get_password_hash, verify_password
from datetime import datetime
from bson import ObjectId

async def get_user_by_username(username: str) -> UserInDB:
    """根据用户名获取用户"""
    db = get_database()
    user_doc = await db["users"].find_one({"username": username})
    if user_doc:
        return UserInDB(**user_doc)
    return None

async def authenticate_user(username: str, password: str) -> User:
    """验证用户"""
    user = await get_user_by_username(username)
    if not user:
        return False
    if not verify_password(password, user.password_hash):
        return False
    # 转换为不包含密码的User对象
    user_dict = user.dict()
    user_dict.pop("password_hash")
    return User(**user_dict)

async def create_user(user: UserCreate) -> User:
    """创建新用户"""
    db = get_database()
    
    # 检查用户是否已存在
    existing_user = await db["users"].find_one({"username": user.username})
    if existing_user:
        raise ValueError("Username already registered")
    
    # 创建用户文档
    user_dict = user.dict()
    user_dict["password_hash"] = get_password_hash(user.password)
    user_dict["created_at"] = datetime.utcnow()
    user_dict["updated_at"] = datetime.utcnow()
    user_dict["last_login"] = None
    user_dict["is_active"] = True
    user_dict["wallet_balance"] = 0.0
    
    # 插入数据库
    result = await db["users"].insert_one(user_dict)
    
    # 获取创建的用户
    created_user = await db["users"].find_one({"_id": result.inserted_id})
    
    # 转换为User对象（不包含密码哈希）
    user_response = created_user.copy()
    user_response.pop("password_hash")
    
    return User(**user_response)